import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_anim_test/utils/app_extends.dart';

class LoadingButtonCtrl {
  late ValueChanged<bool> _valueChanged;
  late ValueGetter<bool> _valueGetter;

  bool get isOn => _valueGetter();

  void toggle(bool isOn) => _valueChanged(isOn);
}

class LoadingButton extends StatefulWidget {
  final double width;
  final double height;
  final double elevation;
  final Color? bgColor;
  final Color? offBgColor;
  final Color? onBgColor;
  final LoadingButtonCtrl? ctrl;
  final Future<bool> Function(bool) onToggle;

  const LoadingButton({
    super.key,
    this.width = 60,
    this.height = 60,
    this.elevation = 4,
    this.bgColor,
    this.offBgColor,
    this.onBgColor,
    required this.onToggle,
    this.ctrl,
  });

  @override
  State<LoadingButton> createState() => _LoadingButtonState();
}

class _LoadingButtonState extends State<LoadingButton> {
  //是否打开
  bool _isOn = false;

  //是否加载中
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    if (widget.ctrl != null) {
      widget.ctrl!._valueChanged = _handleExternalToggle;
      widget.ctrl!._valueGetter = () => _isOn;
    }
  }

  //直接开启或者关闭按钮
  void _handleExternalToggle(bool isOn) {
    //正在Loading 禁止操作
    if (_isLoading) return;
    if (isOn != _isOn) {
      setState(() {
        _isOn = isOn;
      });
    }
  }

  void _onTapClick() async {
    //正在Loading 禁止操作
    if (_isLoading) return;
    //进入Loading
    setState(() => _isLoading = true);
    //触发回调
    final success = await widget.onToggle(_isOn);
    //取消Loading
    setState(() => _isLoading = false);
    //设置结果
    if (success) {
      _isOn = !_isOn;
    }
  }

  Color get _bgColor => _isOn ? widget.onBgColor ?? (widget.bgColor ?? Colors.transparent) : widget.offBgColor ?? (widget.bgColor ?? Colors.transparent);

  double get _minSize => min(widget.width, widget.height);

  @override
  Widget build(BuildContext context) {
    return Material(
      elevation: widget.elevation,
      color: Colors.transparent,
      shape: CircleBorder(),
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        width: widget.width,
        height: widget.height,
        decoration: BoxDecoration(
          color: _bgColor,
          shape: BoxShape.circle,
        ),
        child: _buildContent(),
      ),
    );
  }

  //按钮内容
  Widget _buildContent() {
    return Material(
      type: MaterialType.transparency,
      child: InkWell(
        onTap: _onTapClick,
        splashColor: _bgColor.darken(0.15),
        customBorder: const CircleBorder(),
        child: AnimatedSwitcher(
          duration: const Duration(milliseconds: 300),
          transitionBuilder: (child, animation) => ScaleTransition(
            scale: animation,
            child: FadeTransition(
              opacity: animation,
              child: child,
            ),
          ),
          child: _isLoading
              ? const CircularProgressIndicator(
                  color: Colors.white,
                  strokeWidth: 2,
                )
              : Icon(
                  key: ValueKey(_isOn),
                  _isOn ? Icons.power_settings_new : Icons.power_off,
                  size: _minSize * 0.6,
                  color: Colors.white,
                ),
        ),
      ),
    );
  }
}
